# -*- coding: utf-8 -*-
# https://blog.csdn.net/weixin_52040868
# 公众号：测个der
# 微信：qing_an_an
import json
import requests
from Drawing import Worker
from addict import Dict
from datas import Parameter, Data, DataQueue
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QHeaderView, QVBoxLayout
from PySide6.QtCore import Qt, QTimer
from qfluentwidgets import InfoBar, InfoBarPosition, LineEdit
from resources.LoginUi import Ui_MainWindow
from resources.DataIndex import Ui_IndexWindow


class Index(QMainWindow):
    def __init__(self):
        super(Index, self).__init__()
        self.ui = Ui_IndexWindow()
        self.ui.setupUi(self)


class SetText:
    def __init__(self, example):
        self.example = example

    def set_se_text(self):
        """传入固定的枚举值"""
        self.example.ui.LineUrl.setText(Parameter.TOKEN_URL.value)
        self.example.ui.LineUser.setText(Parameter.ACCOUNT.value)
        self.example.ui.LinePwd.setText(Parameter.PASSWORD.value)


class Show(QMainWindow):

    def __init__(self):
        super(Show, self).__init__()
        self.ui = Ui_MainWindow()   # 主页面，登录页面
        self.index = Index()        # 子页面，数据页面
        self.init_ui()
        self.work = Worker()

    def init_ui(self):
        """初始方法"""
        self.ui.setupUi(self)
        self.ui.BtnLogin.clicked.connect(self.login)
        self.show()
        # self.start_chart()  # 启动子线程
        SetText(self).set_se_text()
        # self.index.ui.BtnQuery.clicked.connect(self.loding)  # 加载html)
        setattr(self, "pie_chart", QWebEngineView(self))
        setattr(self, "bar_chart", QWebEngineView(self))

    def start_chart(self):
        """作图线程"""
        self.index.ui.verticalLayout_5.addWidget(self.bar_chart)    # 插入QWebEngineView
        self.index.ui.verticalLayout_7.addWidget(self.pie_chart)    # 插入QWebEngineView
        self.work.start()
        self.work.get_pie_signal.connect(self.pie_show_view)
        self.work.get_bar_signal.connect(self.bar_show_view)

    def login(self):
        """登录接口"""
        url, user, pwd = self.get_lineedit_text()
        Data['header'] = {"Content-Type": "application/json"}
        res = requests.post(url=url, headers=Data.header, data=json.dumps({"account": user, "password": pwd}))
        Data['token'] = eval(res.text)["token"]
        if Data.token:
            self.close()
            self.createSuccessInfoBar(Data.token)
            self.index.move(120, 30)
            self.after_show()  # 调用接口
            self.index.show()  # 显示页面
            QTimer.singleShot(500, self.start_chart)   # 启动子线程

    def after_show(self):
        """加载子页面数据"""
        self.products()  # 默认发起请求，添加项目选项项目
        self.show_tabel()  # 默认发起请求，对表单添加数据

    def get_lineedit_text(self):
        """搜索二级目录的控件"""
        texts = []
        for child in self.children():
            for value in child.children():
                if isinstance(value, LineEdit):
                    texts.append(value.text())
        return texts

    def products(self):
        """查询项目"""
        # 更新token
        Data.header.update({"token": Data.token})
        res = requests.get(url=Parameter.PRODUCTS_URL.value, headers=Data.header)
        Data["get_products"] = Dict(res.json())  # 更新好Data中
        self.index.ui.ComboProducts.setMaxVisibleItems(5)  # 显示展示数据
        for get_name in Data.get_products.products:
            self.index.ui.ComboProducts.addItem(get_name.name)
        DataQueue.put(Data.get_products)

    def set_table(self, table):
        """制作表单"""
        table.verticalHeader().hide()
        table.setColumnCount(6)
        table.setRowCount(len(Data.get_products.products))
        table.setBorderVisible(True)
        table.setBorderRadius(8)
        table.setWordWrap(False)
        table.setHorizontalHeaderLabels(['项目', 'ID', '总数量', '未解决', '已关闭', '已修改'])
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table.setSortingEnabled(True)
        table.resizeColumnsToContents()

    def show_tabel(self):
        """显示表单"""
        self.set_table(self.index.ui.TableWidget)
        for i, product in enumerate(Data.get_products.products):
            row_data = [product.name, str(product.id), str(product.bugs), str(product.unResolved),
                        str(product.closedBugs), str(product.fixedBugs)]
            for j, data in enumerate(row_data):
                self.index.ui.TableWidget.setItem(i, j, QTableWidgetItem(data))

    def pie_show_view(self, view):
        """饼状图数据渲染"""
        self.pie_chart.setMaximumSize(self.ui.centralwidget.width(), self.index.ui.widget_line.height())  # 设置最大尺寸
        self.pie_chart.setHtml(view.decode())

    def bar_show_view(self, view):
        """柱状图数据渲染"""
        self.bar_chart.setMaximumSize(self.ui.centralwidget.width(), self.index.ui.widget_line.height())  # 设置最大尺寸
        self.bar_chart.setHtml(view.decode())

    def createSuccessInfoBar(self, value):
        # convenient class mothod
        InfoBar.success(
            title='请求成功',
            content=f"Token为 {value}",
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            # position='Custom',   # NOTE: use custom info bar manager
            duration=2000,
            parent=self.index
        )


if __name__ == '__main__':
    app = QApplication([])
    window = Show()
    app.exec()
